package com.tianfeng.huayi.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.aliyuncs.exceptions.ClientException;
import com.tianfeng.huayi.entity.ComplaintManagement;
import com.tianfeng.huayi.entity.RepairRecord;
import com.tianfeng.huayi.service.IRepairRecordService;
import com.tianfeng.huayi.util.CurrentDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import java.io.*;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/repairRecord")
@CrossOrigin
public class RepairRecordController {

    @Autowired
    private IRepairRecordService repairRecordService;
    @Autowired
    private ServletContext servletContext;

    /**
     查询报修列表
     */
    @PostMapping("/list")
    public ResponseEntity<Map<Object, Object>> list(@RequestBody RepairRecord repairRecord) {
        Map<Object,Object> response = new HashMap<>();
        List<RepairRecord> repairRecordList = repairRecordService.selectRepairRecordList(repairRecord);
        if (!repairRecordList.isEmpty()) {
            response.put("code", 200);
            response.put("msg", "查询成功");
            response.put("data", repairRecordList);
        } else {
            response.put("code", 401);
            response.put("msg", "无报修信息");
        }
        return ResponseEntity.ok(response);
    }

    /**
     报修
     */
    @PostMapping("/insert")
    public ResponseEntity<Map<Object, Object>> insert(@RequestBody RepairRecord repairRecord) {
        Map<Object,Object> response = new HashMap<>();
        repairRecord.setRepairTime(CurrentDate.convertLocalDateTimeToDate(LocalDateTime.now()));
        int i = repairRecordService.insertRepairRecord(repairRecord);
        if (i != 0) {
            response.put("code", 200);
            response.put("msg", "报修成功");
        } else {
            response.put("code", 400);
            response.put("msg", "报修失败");
        }
        return ResponseEntity.ok(response);
    }

//    /**
//     * 上传图片
//     */
//    @PostMapping("/putImg")
//    public ResponseEntity<Map<Object, Object>> putImg(@RequestParam("file") MultipartFile file) {
//        String uploadDir = "D:\\Program Files\\JetBrains\\IdeaProjects\\tianfengweapp\\src\\main\\resources\\static\\img\\"; // 指定上传文件保存的路径
//
//        try {
//            // 获取上传文件的原始文件名
//            String fileName = file.getOriginalFilename();
//            // 指定上传文件的保存路径
//            String filePath = uploadDir + fileName;
//            // 将上传的文件保存到指定路径
//            file.transferTo(new File(filePath));
//
//            // 返回成功上传的文件链接
//            String fileUrl = "http://localhost:8080/img/" + fileName;
//
//            // 在这里进行其他业务逻辑处理
//
//            // 返回上传成功的响应
//            Map<Object, Object> response = new HashMap<>();
//            response.put("code", 200);
//            response.put("msg", "上传成功");
//            response.put("fileUrl", fileUrl);
//            return ResponseEntity.ok(response);
//        } catch (IOException e) {
//            e.printStackTrace();
//            // 返回上传失败的响应
//            Map<Object, Object> response = new HashMap<>();
//            response.put("code", 400);
//            response.put("msg", "上传失败");
//            response.put("error", e.getMessage());
//            return ResponseEntity.badRequest().body(response);
//        }
//
//    }

    /**
     * 上传图片
     */
    @PostMapping("/putImg")
    public ResponseEntity<Map<Object, Object>> putImg(@RequestParam("file") MultipartFile file) throws IOException {

        String uploadDir = "D:\\Program Files\\JetBrains\\IdeaProjects\\tianfengweapp\\src\\main\\resources\\static\\img\\"; // 指定上传文件保存的路径
        // 获取上传文件的原始文件名
        String fileName = file.getOriginalFilename();
        // 指定上传文件的保存路径
        String filePaths = uploadDir + fileName;
        // 将上传的文件保存到指定路径
        file.transferTo(new File(filePaths));

        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 填写自己的id和密钥
        String accessKeyId = "LTAI5tHExsDP6bFns7iwLAZe";
        String accessKeySecret = "J3UzFIUkqJK9ee1YjFxnhdPEuSuFrO";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "lwh-tianfeng";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "repairimg/" + fileName;
        // 填写本地文件的完整路径，例如D:\\localpath\\examplefile.txt。
        // 如果未指定本地路径，则默认从示例程序所属项目对应本地路径中上传文件。
        String filePath = "D:\\Program Files\\JetBrains\\IdeaProjects\\tianfengweapp\\src\\main\\resources\\static\\img" + File.separator + file.getOriginalFilename();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        Map<Object, Object> response = new HashMap<>();
        try {
            InputStream inputStream = new FileInputStream(filePath);
            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName, inputStream);
            // 创建PutObject请求。
            PutObjectResult result = ossClient.putObject(putObjectRequest);
            String fileUrl = endpoint.split("//")[0] + "//" + bucketName + "." + endpoint.split("//")[1] + "/" + objectName;
            System.out.println(fileUrl);
            File fileToDelete = new File(uploadDir + fileName);
            fileToDelete.delete();
            response.put("code", 200);
            response.put("msg", "上传成功");
            response.put("fileUrl", fileUrl);
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return ResponseEntity.ok(response);
    }



//    /**
//     * 删除图片
//     */
//    @PostMapping("/delImg")
//    public ResponseEntity<Map<Object, Object>> delImg(@RequestBody Map<String, Object> requestBody) {
//        String fileName = (String) requestBody.get("fileName");
//        String uploadDir = "D:\\Program Files\\JetBrains\\IdeaProjects\\tianfengweapp\\src\\main\\resources\\static\\img\\"; // 指定上传文件保存的路径
//        File fileToDelete = new File(uploadDir + fileName);
//
//        Map<Object, Object> response = new HashMap<>();
//        if (fileToDelete.delete()) {
//            response.put("code", 200);
//            response.put("msg", "删除成功");
//            return ResponseEntity.ok(response);
//        } else {
//            response.put("code", 400);
//            response.put("msg", "删除失败");
//            return ResponseEntity.badRequest().body(response);
//        }
//    }

    /**
     * 删除图片
     */
    @PostMapping("/delImg")
    public ResponseEntity<Map<Object, Object>> delImg(@RequestBody Map<String, Object> requestBody) throws ClientException {
        String fileName = (String) requestBody.get("fileName");
        Map<Object, Object> response = new HashMap<>();
        // Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 填写自己的id和密钥
        String accessKeyId = "LTAI5tHExsDP6bFns7iwLAZe";
        String accessKeySecret = "J3UzFIUkqJK9ee1YjFxnhdPEuSuFrO";
        // 填写Bucket名称，例如examplebucket。
        String bucketName = "lwh-tianfeng";
        // 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
        String objectName = "repairimg/" + fileName;
        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, objectName);
            response.put("code", 200);
            response.put("msg", "删除成功");
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
        return ResponseEntity.ok(response);
    }
}
